<?php

namespace App\Services;

use Log;
use Illuminate\Support\Facades\Redis;

class WXServices
{
    public static $OK = 0;
    public static $IllegalAesKey = -41001;
    public static $IllegalIv = -41002;
    public static $IllegalBuffer = -41003;
    public static $DecodeBase64Error = -41004;

    private static function sendUrl($url)
    {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);

        return $output;
    }

    // 登录
    public static function login($code)
    {
        $url  = 'https://api.weixin.qq.com/sns/jscode2session';
        $data = [
            'appid'      => "wx820e151d0905ab1a",
            'secret'     => "60e60ad4e4cd75996aec80b104e41964",
            'js_code'    => $code,
            'grant_type' => 'authorization_code',
        ];

        $url = $url . '?' . http_build_query($data);
        $res = self::sendUrl($url);
        $res = json_decode($res);

        if (isset($res->openid)) {
            Redis::setex($res->openid, 7200, $res->session_key);
            return $res->openid;
        } else {
            return "Error";
        }
    }

    public static function getPhone($data, $iv, $openid)
    {
        $decryptData = self::decryptData($data, $iv, $openid, $data);

        if (isset($decryptData->phoneNumber)) {
            return $decryptData->purePhoneNumber;
        } else {
            return "";
        }

    }

    private static function decryptData($encryptedData, $iv, $openid, &$data)
    {
        if (strlen(Redis::get($openid)) != 24) {
            return self::$IllegalAesKey;
        }
        $aesKey = base64_decode(Redis::get($openid));

        if (strlen($iv) != 24) {
            return self::$IllegalIv;
        }
        $aesIV = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);
        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj = json_decode($result);
        if ($dataObj == null) {
            return self::$IllegalBuffer;
        }
        return $dataObj;
    }
}